<template>
  <view class="container">
    <z-paging-swiper>
      <view slot="top">
        <u-navbar
          height="50"
          :border-bottom="false"
          title="交易订单"
          title-size="36"
          title-color="#333"
        ></u-navbar>
        <view class="tabsView">
          <u-tabs-swiper
            ref="uTabs"
            :list="tabsList"
            :current="current"
            @change="tabsChange"
            :is-scroll="false"
            :show-bar="false"
            active-color="#10A28F"
            swiper-width="750"
          >
          </u-tabs-swiper>
        </view>
        <u-gap height="20" bg-color="#F0F1F2"></u-gap>
      </view>
      <swiper
        class="swiperView"
        :current="scurrent"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <swiper-item v-for="(_sitem, sindex) in tabsList" class="swiperItem" :key="sindex">
          <z-paging
            ref="paging"
            v-model="itemList[sindex]"
            @query="queryList"
            :fixed="true"
            :auto="false"
            :auto-show-back-to-top="true"
            :empty-view-img="`${getImageUrl('empty.png')} `"
            empty-view-text="暂无订单数据~"
            :empty-view-img-style="imgStyle"
          >
            <view class="goodsItemView">
              <view
                class="itemView"
                v-for="(item, index1) in itemList[sindex]"
                :key="index1"
                @click="onOrderDetail(item)"
              >
                <view class="order-top dis-flex flex-y-center flex-y-between">
                  <view
                    class="dis-flex flex-y-center"
                    v-if="item.shop"
                    @click.stop.prevent="onShop(item.shop)"
                  >
                    <u-image
                      class="goods-img"
                      style="margin-right: 20rpx; border: 1rpx solid #999999"
                      :src="item.shop.logo"
                      width="60rpx"
                      height="60rpx"
                      border-radius="30"
                    ></u-image>
                    <text>{{ item.shop.name }}</text>
                  </view>
                  <view class="order-top-tip">
                    <text
                      v-if="item.type === 10"
                      style="font-weight: bold; font-size: 28rpx; margin-right: 20rpx"
                      >外卖
                    </text>
                    <text
                      v-if="item.reserveDate"
                      style="
                        color: #cb6501;
                        font-weight: bold;
                        font-size: 28rpx;
                        margin-right: 20rpx;
                      "
                      >预约</text
                    >
                    <text
                      v-if="
                        item.dineStatus === 22 || item.dineStatus === 30 || item.dineStatus === 40
                      "
                      style="color: orange"
                      >{{ item.statusName }}</text
                    >
                    <text v-else>{{ item.statusName }}</text>
                  </view>
                </view>
                <view class="layoutView">
                  <view class="order-goods" v-for="item2 in item.items" :key="item2.id">
                    <u-image
                      class="goods-img"
                      :src="item2.picUrl"
                      width="160rpx"
                      height="160rpx"
                      border-radius="10"
                    ></u-image>
                    <view class="orde-riget" style="flex: 1">
                      <view class="goods-title">
                        <text>{{ item2.spuName }}</text>
                      </view>
                      <view class="goods-speci dis-flex flex-x-baseline">
                        <text v-if="item2.properties && item2.properties.length > 0"
                          >{{ item2.properties[0].valueName }}
                        </text>
                        <text class="goodsNum" style="margin-left: 20rpx"
                          >{{ item2.count }}{{ item2.unitValue > 1 ? 'x' + item2.unitValue : ''
                          }}{{ item2.unitName || '' }}
                        </text>
                        <view class="flex-1"></view>
                        <text class="goodsNum" v-if="item2.weight"
                          >约{{ (item2.count * item2.weight * 1000).toFixed(0) }}克
                        </text>
                      </view>
                      <view class="goods-price" v-if="item2.afterSaleId">
                        <text>¥{{ (item2.price * 0.01).toFixed(2) }}</text>
                        <text
                          class="goods-refund"
                          v-if="
                            item2.afterSaleStatus === 10 ||
                            item2.afterSaleStatus === 20 ||
                            item2.afterSaleStatus === 30
                          "
                        >
                          退款进行中
                        </text>
                        <text class="goods-refund" v-else-if="item2.afterSaleStatus === 40">
                          等待平台退款
                        </text>
                        <text class="goods-refund" v-else-if="item2.afterSaleStatus === 50">
                          退款成功
                        </text>
                        <text class="goods-refund" v-else> 已终止退款</text>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="price-total dis-flex flex-y-center flex-y-between">
                  <view>共{{ item.items.length }}样</view>
                  <view>
                    合计：
                    <text style="color: #fa453c">¥{{ (item.payPrice * 0.01).toFixed(2) }}</text>
                  </view>
                </view>
                <view class="btn-group" v-if="item.dineStatus == 20 || item.dineStatus == 22">
                  <view class="hollow-btn btn" @click.stop.prevent="onOrderDetail(item)">
                    等待出餐</view
                  >
                </view>
                <view class="btn-group" v-else-if="item.dineStatus == 30 && item.riderStaffId">
                  <view class="solid-btn btn" @click.stop.prevent="onMealsPickup(item)">
                    我已取餐</view
                  >
                </view>
                <view class="btn-group" v-else-if="item.dineStatus == 40 && item.riderStaffId">
                  <view class="warning-btn btn" @click.stop.prevent="onMealsArrive(item)">
                    我已送达</view
                  >
                </view>
                <view class="btn-group" v-else>
                  <view @click.stop.prevent="onOrderDetail(item)" class="hollow-btn btn">
                    查看详情
                  </view>
                </view>
              </view>
            </view>
          </z-paging>
        </swiper-item>
      </swiper>
    </z-paging-swiper>

    <u-popup
      :closeable="true"
      width="550rpx"
      v-model="arrivePopup"
      mode="bottom"
      height="auto"
      border-rad
      border-radius="15"
      z-index="998"
    >
      <view class="popup-box">
        <view class="popup-title"> 送达凭证</view>
        <view class="image-group">
          <view class="dis-flex">
            <text style="color: red">*</text>
            <text>图片</text>
            <text style="color: #999999">（{{ fileList ? fileList.length : 0 }}/3）</text>
          </view>
          <view class="" style="margin-top: 20rpx">
            <u-upload
              :custom-btn="true"
              :action="action"
              max-count="3"
              ref="uUpload"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              @on-remove="onFileRemove"
            >
              <view
                slot="addBtn"
                class="slot-btn"
                hover-class="slot-btn__hover"
                hover-stay-time="150"
              >
                <u-icon name="/static/xj.png" size="80"></u-icon>
                <view style="color: #999999">添加图片</view>
              </view>
            </u-upload>
          </view>
        </view>
        <view style="margin-top: 20rpx">
          <u-input
            type="textarea"
            v-model="form1.remark"
            placeholder="请输入备注"
            maxlength="200"
            height="80"
            :border="true"
            :clearable="true"
          ></u-input>
        </view>
        <!-- 快捷输入标签 -->
        <view class="quick-tags">
          <view class="tags-title">常用备注快捷输入：</view>
          <view class="tags-container">
            <view
              v-for="(tag, index) in quickRemarkTags"
              :key="index"
              class="tag-item"
              :class="{ active: selectedRemarkTags.includes(tag) }"
              @click="toggleRemarkTag(tag)"
            >
              {{ tag }}
            </view>
          </view>
        </view>
        <view class="" style="margin-bottom: 100rpx"></view>
        <view class="fixed-wapper1">
          <view class="submit-btn" @click="performMealsArrive"> 确认送达</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { BASE_URL, UP_URL } from '@/common/config'

export default {
  data() {
    return {
      imgStyle: {
        width: '12rem'
      },
      expressPopup: false,
      expressPicker: false,
      arrivePopup: false,
      current: 0,
      scurrent: 0,
      tabsList: [
        {
          name: '全部',
          status: ''
        },
        {
          name: '派单中',
          status: 20
        },
        {
          name: '已派单',
          status: 22
        },
        {
          name: '已出餐',
          status: 30
        },
        {
          name: '配送中',
          status: 40
        },
        {
          name: '已送达',
          status: 50
        }
      ],
      itemList: [[], [], [], [], [], []],
      action: BASE_URL + UP_URL,
      fileList: [],
      form1: {
        id: null,
        picUrls: [],
        remark: ''
      },
      quickRemarkTags: [
        '已挂门把手上',
        '已放家门口',
        '已放公司前台',
        '已放门卫处',
        '客户电话联系不上'
      ],
      selectedRemarkTags: [],
      order_id: ''
    }
  },
  onLoad(res) {
    if (res.index) {
      this.current = Number(res.index) ? Number(res.index) : 0
      this.scurrent = Number(res.index) ? Number(res.index) : 0
    }
    if (res.status) {
      let _index = this.tabsList.findIndex((item) => item.status == res.status)
      console.log(_index, res.status)
      this.current = _index ? _index : 0
      this.scurrent = _index ? _index : 0
    }
  },
  onShow() {
    this.queryList()
  },
  methods: {
    tabsChange(index) {
      this.scurrent = index
    },
    transition(e) {
      let dx = e.detail.dx
      this.$refs.uTabs.setDx(dx)
    },
    animationfinish(e) {
      this.current = e.detail.current
      this.scurrent = e.detail.current
      this.$refs.uTabs.setFinishCurrent(e.detail.current)
      if (this.itemList[this.current].length == 0) {
        this.queryList(1)
      }
    },
    queryList(pageNo = 1, pageSize = 10) {
      if (pageNo === 1) {
        this.itemList[this.current] = []
      }
      this.$u
        .get('/app-api/trade/order/page-rider', {
          pageNo,
          pageSize,
          dineStatus: this.tabsList[this.scurrent].status
        })
        .then((res) => {
          this.$refs.paging[this.scurrent].complete(res.data.list)
        })
        .catch(() => {
          this.$refs.paging[this.scurrent].complete(false)
        })
    },
    beforeFileUpload(_index, list) {
      this.fileList = list
    },
    onFileRemove(_index, list) {
      this.fileList = list
    },
    onMealsPickup(item) {
      uni.showModal({
        title: '配送提示',
        content: `确定已到店取到餐了吗？`,
        success: (res) => {
          if (res.confirm) {
            this.performMealsPickup(item)
          }
        }
      })
    },
    performMealsPickup(item) {
      uni.showLoading()
      const self = this
      self.$u
        .post('/app-api/trade/order/pickup?id=' + item.id)
        .then((res) => {
          uni.hideLoading()
          if (res.code === 0) {
            self.queryList(1)
          } else {
            self.$u.toast(res.msg)
          }
        })
        .catch(() => {
          uni.hideLoading()
        })
    },
    onMealsArrive(item) {
      this.form1.id = item.id
      this.arrivePopup = true
    },
    toggleRemarkTag(tag) {
      const index = this.selectedRemarkTags.indexOf(tag)
      if (index > -1) {
        // 如果标签已选中，则移除
        this.selectedRemarkTags.splice(index, 1)
      } else {
        // 如果标签未选中，则添加
        this.selectedRemarkTags.push(tag)
      }
      // 更新备注内容
      this.updateRemarkWithTags()
    },
    updateRemarkWithTags() {
      // 保留用户手动输入的内容，只更新标签部分
      let remark = this.form1.remark
      // 移除之前添加的标签（如果有）
      this.quickRemarkTags.forEach((tag) => {
        remark = remark.replace(`【${tag}】`, '')
      })
      // 清理多余空格和逗号
      remark = remark.trim()
      // 添加当前选中的标签
      if (this.selectedRemarkTags.length > 0) {
        const tagsText = this.selectedRemarkTags.map((tag) => `【${tag}】`).join(' ')
        remark = tagsText + (remark ? ' ' + remark : '')
      }
      this.form1.remark = remark
    },
    performMealsArrive() {
      let self = this
      self.$refs.uUpload.lists.forEach((val) => {
        self.form1.picUrls.push(val.response.data)
      })
      if (!self.form1.picUrls || !self.form1.picUrls.length) {
        self.$u.toast('请上传凭证图片')
        return
      }
      self.$u.post('/app-api/trade/order/arrive', self.form1).then((res) => {
        if (res.code === 0) {
          self.fileList = []
          self.form1.id = null
          self.form1.picUrls = []
          self.form1.remark = ''
          self.selectedRemarkTags = [] // 清空选中的标签
          self.queryList(1)
          setTimeout(function () {
            self.arrivePopup = false
          }, 200)
        } else {
          self.$u.toast(res.msg)
        }
      })
    },
    onOrderDetail(item) {
      this.$utils.route({
        url: '/rider/order-details/order-details',
        params: {
          id: item.id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('order-list.css');
@import url('@/style/btn.css');

.slot-btn {
  width: 200rpx;
  height: 200rpx;
  background: #f5f5f5;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-flow: column;
}

.quick-tags {
  margin-top: 20rpx;

  .tags-title {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 15rpx;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;

    .tag-item {
      padding: 8rpx 20rpx;
      background-color: #f5f5f5;
      border-radius: 30rpx;
      border: 1px solid #10a28f;
      font-size: 24rpx;
      color: #10a28f;

      &.active {
        background-color: #10a28f;
        color: #ffffff;
      }
    }
  }
}
</style>
